/*
 * @Author: WuFeng <763467339@qq.com>
 * @Date: 2022-03-22 12:12:49
 * @LastEditTime: 2023-03-14 19:58:15
 * @LastEditors: WuFeng <763467339@qq.com>
 * @Description: 用户登录相关接口
 * @FilePath: \vue3-element-plus-web\src\api\login.js
 * @Copyright 版权声明
 */
import { randomString } from '@/utils'
import request from '@/utils/request'
import qs from 'qs'

/**
 * @description 生成按钮权限
 * @param {Object} params
 */
const generateHandleAuth = (item) => {
  const { scope, children } = item
  const handleAuth = {}
  // 新增 权限
  if (scope.charAt(0) === '1') {
    handleAuth['CREATE'] = true
  }
  // 删除 权限
  if (scope.charAt(1) === '1') {
    handleAuth['DELETE'] = true
  }
  // 修改 权限
  if (scope.charAt(2) === '1') {
    handleAuth['UPDATE'] = true
  }
  // 查看 权限
  if (scope.charAt(3) === '1') {
    handleAuth['DETAIL'] = true
  }

  // 如果有子级，继续往下遍历寻找【按钮】
  if (children) {
    for (const row of children) {
      if (row.category === 2) {
        const buttonAuthName = ((row.code).replaceAll('.', '')).toUpperCase()
        handleAuth[buttonAuthName] = true
      }
    }
  }
  return handleAuth
}

// 图片验证码
export function getVerifyCode() {
  // return process.env.VUE_APP_API_URL + '/captcha?' + Math.random()
  const data = {}
  return request({
    url: '/captcha?' + Math.random(),
    method: 'get',
    data
  })
}

/**
 * @description 发送短信验证码
 * @param {Object} params
 */
export function sendSmsVerificationCode(params) {
  params
  return new Promise(function(resolve) {
    resolve({
      message: '\u7b7e\u540d\u8fc7\u671f',
      data: {
        token: 'admin'
      },
      resType: '200'
    })
  })
  // const data = {
  //   reqType: 'LOGIN',
  //   data: {
  //     item: {
  //       accountName: params.username,
  //       accountPwd: params.password
  //     }
  //   }
  // }
  // const loginData = request({
  //   url: '/login',
  //   method: 'post',
  //   data
  // })
  // return loginData
}

/**
 * @description 登陆
 * @param {Object} params
 */
export function login(params) {
  // params
  // return new Promise(function(resolve) {
  //   resolve({
  //     message: '\u7b7e\u540d\u8fc7\u671f',
  //     data: {
  //       token: 'admin'
  //     },
  //     resType: '200'
  //   })
  // })
  const data = params
  const loginData = request({
    url: '/sys/login ',
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    data: qs.stringify(data)
  })
  return loginData
}

/**
 * @description 获取登录用户信息及拥有的权限信息
 * @param {Object} params
 */
export async function getInfo() {
  // return new Promise(function(resolve) {
  //   resolve({
  //     message: '\u6210\u529f',
  //     data: {
  //       avatar:
  //         'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
  //       name: '超级管理员',
  //       menus: []
  //       // menus: [
  //       //   {
  //       //     children: [
  //       //       {
  //       //         component: 'layout.inline',
  //       //         hidden: false,
  //       //         meta: {
  //       //           handleAuth: { ADD: true, SET_ROLE: true, EDIT: true },
  //       //           title: '账户管理',
  //       //           icon: 'user'
  //       //         },
  //       //         name: 'UserIndex',
  //       //         path: '/user-w',
  //       //         resourceUrl: '',
  //       //         children: [
  //       //           {
  //       //             children: [],
  //       //             component: 'setting.system',
  //       //             hidden: false,
  //       //             meta: {
  //       //               handleAuth: { ADD: true, SET_ROLE: true, EDIT: true },
  //       //               title: '系统设置'
  //       //             },
  //       //             name: 'SettingSystem',
  //       //             path: '/setting-system',
  //       //             resourceUrl: ''
  //       //           }
  //       //         ]
  //       //       },
  //       //       {
  //       //         children: [],
  //       //         component: 'user.index',
  //       //         hidden: false,
  //       //         meta: {
  //       //           handleAuth: { EDIT_SAVE: true },
  //       //           icon: 'yanzhengma',
  //       //           title: '角色控制权限'
  //       //         },
  //       //         name: 'RoleAuthorize',
  //       //         path: '/role-authorize',
  //       //         resourceUrl: ''
  //       //       }
  //       //     ],
  //       //     component: 'layout.inline',
  //       //     hidden: false,
  //       //     meta: { icon: 'yanzhengma', title: '权限管理' },
  //       //     name: 'qxgl',
  //       //     path: '/qxgl'
  //       //   },
  //       //   {
  //       //     children: [],
  //       //     component: 'user.index',
  //       //     hidden: false,
  //       //     meta: {
  //       //       handleAuth: { ADD: true, DEL: true, EDIT: true },
  //       //       icon: 'my-shezhi',
  //       //       title: '代码表维护'
  //       //     },
  //       //     name: 'XtdmIndex',
  //       //     path: '/xtdm',
  //       //     resourceUrl: ''
  //       //   }
  //       // ]
  //     },
  //     resType: '200'
  //   })
  // })

  // const data = {}
  // return request({
  //   url: '/info',
  //   method: 'get',
  //   data
  // })

  const infoRes = await request({
    url: '/info',
    method: 'get',
    data: {}
  })

  const infoResData = infoRes.data || {
    user: {},
    menu: []
  }

  const { user, menu } = infoResData

  // console.log('--menu', menu)

  // 组装菜单数据为系统集成可用的数据
  const menuArr = []
  for (const i in menu) {
    const item = menu[i]
    // console.log('---top menu', item)
    // 一级菜单
    let topMenuName = '' // 菜单名称
    let topMenuComponent = '' // 菜单页面组件
    let topMenuPath = '' // 菜单路径
    let topMenuFullpath = '' // 菜单全路径
    if ((item.path).indexOf('http://') > -1 || (item.path).indexOf('https://') > -1) {
      const topTempStr = randomString(10)
      topMenuName = topTempStr
      topMenuComponent = 'Iframe'
      topMenuPath = `/${item.code}/iframe`
      topMenuFullpath = `/${item.code}/iframe?target=${encodeURIComponent(item.path)}`
    } else {
      if (item.path === '#') {
        const topTempStr = randomString(10)
        topMenuName = topTempStr
        topMenuComponent = `${topTempStr}`
        topMenuPath = `/${topTempStr}`
      } else {
        topMenuName = (item.path).replaceAll('/', '') // 菜单名称
        let topMenuComponentTemp = item.path
        const topMenuComponentFirstChar = topMenuComponentTemp.substr(0, 1)
        const topMenuComponentLastChar = topMenuComponentTemp.charAt(topMenuComponentTemp.length - 1)

        if (topMenuComponentFirstChar === '/') {
          topMenuComponentTemp = topMenuComponentTemp.substr(1, topMenuComponentTemp.length - 1)
        }

        if (topMenuComponentLastChar === '/') {
          topMenuComponentTemp = topMenuComponentTemp.substr(0, topMenuComponentTemp.length - 1)
        }

        topMenuComponent = topMenuComponentTemp.replaceAll('/', '.')
        topMenuPath = item.path
      }
    }
    topMenuName
    const topMenu = {
      fullpath: topMenuFullpath,
      component: topMenuComponent,
      hidden: false,
      meta: {
        icon: item.source,
        title: item.name,
        isOpen: item.isOpen === 1
      },
      // name: topMenuName,
      name: item.code,
      path: topMenuPath
    }
    // 生成按钮权限
    topMenu.meta.handleAuth = generateHandleAuth(item)

    // console.log('--topMenu', topMenu)
    // 二级菜单
    if (item.children && item.children.length > 0) {
      let secondMenuCount = 0
      // 遍历一级菜单下的资源
      for (const ii in item.children) {
        const items = item.children[ii]
        if (items.category === 1) {
          secondMenuCount++
        }
      }
      if (secondMenuCount === 0) {
        // 将一级菜单塞入顶级菜单
        menuArr.push(topMenu)
        continue
      }
      topMenu.children = []
      topMenu.component = 'layout.inline'
      // 遍历二级菜单
      for (const ii in item.children) {
        const items = item.children[ii]

        let secondMenuName = '' // 菜单名称
        let secondMenuComponent = '' // 菜单页面组件
        let secondMenuPath = '' // 菜单路径
        let secondMenuFullpath = '' // 菜单全路径
        if ((items.path).indexOf('http://') > -1 || (items.path).indexOf('https://') > -1) {
          const secondTempStr = randomString(10)
          topMenuName = secondTempStr
          secondMenuComponent = 'Iframe'
          secondMenuPath = `/${items.code}/iframe`
          secondMenuFullpath = `/${items.code}/iframe?target=${encodeURIComponent(items.path)}`
        } else {
          if (items.path === '#') {
            const secondTempStr = randomString(10)
            secondMenuName = secondTempStr
            secondMenuComponent = `${secondTempStr}`
            secondMenuPath = `/${secondTempStr}`
          } else {
            secondMenuName = (items.path).replaceAll('/', '') // 菜单名称
            let secondMenuComponentTemp = items.path
            const secondMenuComponentFirstChar = secondMenuComponentTemp.substr(0, 1)
            const secondMenuComponentLastChar = secondMenuComponentTemp.charAt(secondMenuComponentTemp.length - 1)

            if (secondMenuComponentFirstChar === '/') {
              secondMenuComponentTemp = secondMenuComponentTemp.substr(1, secondMenuComponentTemp.length - 1)
            }

            if (secondMenuComponentLastChar === '/') {
              secondMenuComponentTemp = secondMenuComponentTemp.substr(0, secondMenuComponentTemp.length - 1)
            }

            secondMenuComponent = secondMenuComponentTemp.replaceAll('/', '.')
            secondMenuPath = items.path
          }
        }

        // const secondMenuButtons = [] // 二级菜单按钮集合
        // 二级菜单
        secondMenuName
        const secondMenu = {
          fullpath: secondMenuFullpath,
          component: secondMenuComponent,
          hidden: false,
          meta: {
            handleAuth: {},
            title: items.name,
            isOpen: items.isOpen === 1
          },
          // name: secondMenuName,
          name: items.code,
          path: secondMenuPath
        }

        // 生成按钮权限
        secondMenu.meta.handleAuth = generateHandleAuth(items)

        // 将二级菜单塞入一级菜单
        topMenu.children.push(secondMenu)
      }
    }
    // 将一级菜单塞入顶级菜单
    menuArr.push(topMenu)
  }

  const resData = {
    code: 200,
    msg: '\u6210\u529f',
    data: Object.assign({}, {
      userInfo: user,
      avatar: user.avatar || 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
      name: user.name,
      menus: menuArr
    })
  }
  // console.log('----------menuArr---------', menuArr)
  return new Promise(function(resolve) {
    resolve(resData)
  })
}

/**
 * @description 退出登录
 * @param {*} params
 */
export function logout() {
  // return new Promise(function(resolve) {
  //   resolve({
  //     message: '\u7b7e\u540d\u8fc7\u671f',
  //     data: {},
  //     resType: '200'
  //   })
  // })
  return request({
    url: '/logout',
    method: 'get',
    data: {}
  })
}

/**
 * @description 检测是否登陆
 * @param {*} params
 */
export function checkLogin() {
  const data = {}
  return request({
    url: '/logincheck',
    method: 'post',
    data
  })
}

/**
 * @description 修改密码
 * @param {*} params
 */
export function changePassword(data) {
  return request({
    url: '/sysUser/updatePwd',
    method: 'post',
    data
  })
}

/**
 * @description 选择/切换角色，刷新token
 * @param {String} roleId 角色id
 */
export function selectRole(data) {
  return request({
    url: '/selectRole',
    method: 'get',
    params: data
  })
}
